// pages/orderDetail/orderDetail.js
import config from '../../config.js';
var util = require('../../utils/util.js');
const base = config;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderId: null,
    order: null,
    couponItemList: [],
    coupon: null,
    tip: '',
    orderStatus: [],
    user: wx.getStorageSync("user"),
    // 功能列表
    funList: [{
        icon: "../../image/guanjia/chexian.png",
        text: "车险报价",
        url: "../insurance/insurance"
      }, {
        icon: "../../image/guanjia/shiguxiezhu.png",
        text: "事故协助",
        url: "../accidentAssi/accidentAssi"
      }, {
        icon: "../../image/guanjia/weizhangbanli.png",
        text: "违章办理",
        url: "../peccancy/step2"
      }, {
        icon: "../../image/guanjia/daiweixiu.png",
        text: "代维修",
        url: "../repair/repair"
      }, {
        icon: "../../image/guanjia/daibaoyang.png",
        text: "代保养",
        url: "../maintenance/maintenance"
      }, {
        icon: "../../image/guanjia/jiesongji.png",
        text: "接送机",
        url: "../airport/airport"
      }, {
        icon: "../../image/guanjia/daibuche.png",
        text: "代步车",
        url: "../stepcar/stepcar"
      },
      {
        icon: "../../image/guanjia/dainianjian.png",
        text: "代年检",
        url: "../yearaudit/yearaudit"
      }, {
        icon: "../../image/guanjia/dainianjian.png",
        text: "代年检",
        url: "../yearaudit/yearaudit"
        //url: "../rescure/rescure"
      },
      {
        icon: "../../image/guanjia/gengduo.png",
        text: "其他",
        url: "../others/others"
      }
    ],
  },
  //支付：
  pay: function() {
    var that = this
    var openId = wx.getStorageSync("openID");
    if (openId == null || openId == "") {
      wx.login({
        success: function (res) {
          wx.request({
            url: base.CheckOpenId,
            data: {
              code: res.code
            },
            success: function (res) {
              console.log("openId" + res.data.data.openid);
              wx.setStorageSync('openID', res.data.data.openid);
              // if (wx.getStorageSync("session") == null) {
              //   wx.setStorageSync("session", res.data.session);
              //   console.log("session:" + res.data.session);
              // }
              openId = res.data.data.openid;
              that.payOrder(openId);

            }
          })
        }
      })
    } else {
      that.payOrder(openId);
    }
  },
  payOrder: function (openId) {
    var that = this;
    var orderId = that.data.orderId;
    console.log(orderId);
    wx.showLoading({
      title: '发起支付...',
    })
    wx.request({
      url: base.orderPay,
      data: {
        //用户的openid
        openId: openId,
        orderId: orderId, //
      },
      success: function (result) {
        console.log(result);
        wx.hideLoading();
        if (result.data.status == 200) {
          //out_trade_no=res.data['out_trade_no'];
          wx.requestPayment({
            timeStamp: result.data.timeStamp,
            nonceStr: result.data.nonceStr,
            package: result.data.package,
            signType: 'MD5',
            paySign: result.data.paySign,
            success: function (successret) {
              console.log('支付成功');
              //获取支付用户的信息
              wx.showLoading({
                title: '支付成功！',
              })
              setTimeout(function () {
                that.payResult(orderId, result.data.orderNo);
                wx.hideLoading();
              }, 300);

            },
            fail: function (res) {
              console.log(res);

              wx.showToast({
                title: '支付取消！',
                icon: 'none',
                duration: 1000
              })

            }
          })
        } else {
          console.log();
        }
      }
    })
  },
  payResult: function(id, No) {
    var that = this;
    wx.showLoading({
      title: '更新订单...',
    })
    wx.request({
      url: base.orderPayResult,
      data: {
        //用户的openid
        orderId: id,
        orderNo: No,
        type:2
      },
      success: function(result) {
        console.log(result);
        wx.hideLoading();
        if (result.data.status == 200) {
          wx.showLoading({
            title: '订金支付成功',
          })
          that.loadData();
          setTimeout(function() {
            wx.hideLoading();

          }, 300);

        } else if (result.data.status == 201) {
          //订单更新失败；
          //记录当前订单OrderId;
          wx.setStorageSync("payError", id);
        }
      }
    })
  },
  goMain: function() {
    wx.switchTab({
      url: "../index/index",
    })
  },
  goDetail: function() {
    var that = this;
    wx.setStorageSync("orderId", that.data.orderId);
    wx.setStorageSync("orderConfirmType", 1);
    wx.switchTab({
      url: "../order/order",
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var id = options.id;
    if (id != null) {
      this.setData({
        orderId: id
      })

      // this.getTraceList();
    }


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var coupon = wx.getStorageSync("coupon");
    if (coupon != null) {
      console.log(coupon);

      this.onCouponSet(coupon);
      wx.setStorageSync("coupon", null);
    }
    this.loadData();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    wx.navigateBack({
      delta: 1
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  loadData() {
    var that = this;
    //获取订单详情
    wx.request({
      url: base.orderDetailUrl,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Cookie': wx.getStorageSync("session")
      },
      data: {
        id: this.data.orderId,
        type: 1
      },
      method: "POST",
      success: function(res) {
        console.log(res.data);
        if (res.data.status == 200) {
          that.setData({
            order: res.data.data
          })
          that.getTraceList();
        } else {
          wx.showToast({
            title: '订单获取失败！',
            icon: 'none',
            duration: 1500
          })
          return false;
        }
      }

    })
  },
  getTraceList() {
    var that = this;
    //获取订单详情
    wx.request({
      url: base.feeItems,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Cookie': wx.getStorageSync("session")
      },
      data: {
        id: this.data.orderId
      },
      method: "POST",
      success: function(res) {
        console.log(res.data);
        if (res.data.status == 200) {
          if (res.data.data != null) {
            that.setData({
              items: res.data.data
            })
          }

          that.loadCouponList();

        } else {
          wx.showToast({
            title: '订单获取失败！',
            icon: 'none',
            duration: 1500
          })
          return false;
        }
      }

    })
  },
  loadCouponList: function() {
    var that = this;
    //获取支付项目
    wx.request({
      url: base.getCouponList,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Cookie': wx.getStorageSync("session")
      },
      data: {
        typeId: this.data.order.order.orderType.typeId,
        orderId: that.data.orderId
      },
      method: "POST",
      success: function(res) {
        console.log(res.data);
        if (res.data.status == 200) {
          if (res.data.data != null) {
            console.log(res.data.data);
            for (var i = 0; i < res.data.data.length; i++) {
              var item = res.data.data[i];
              if (item.memberRights != null && item.memberRights.memberRightType.typeId == 2) {
                item.memberRights.price = util.numberFormat(item.memberRights.price * 10,2);
                res.data.data[i] = item;
              }

            }
            that.setData({
              couponItemList: res.data.data,
            })

            that.onCouponSet(res.data.data[0]);
          }

        } else {}
      }

    })
  },
  chooseCoupon: function() {
    var orderId = this.data.orderId;
    var typeId = this.data.order.order.orderType.typeId;
    wx.navigateTo({
      url: '../orderDetail/coupomItems?orderId=' + orderId + "&typeId=" + typeId,
    })
  },
  onCouponSet: function(item) {
    if (item != null && item.memberRights != null) {
      var totalPrice = this.data.order.order.totalPrice;
      console.log(item)
      item.memberRights.price = util.numberFormat(item.memberRights.price,2);
      //折算
      var tip = '';
      if (item.memberRights.memberRightType.typeId == 1) {
        //次数
        tip = "" + totalPrice + "-" + item.memberRights.price + "=";
        if (totalPrice > item.memberRights.price) {
          totalPrice -= item.memberRights.price;
        } else {
          totalPrice = 0;
        }
        totalPrice = util.numberFormat(totalPrice,2);
      } else {
        //折扣
        tip = "" + totalPrice + "*" + item.memberRights.price + "折=";
        totalPrice = this.data.totalOrPrice * item.memberRights.price / 10;
        totalPrice = util.numberFormat(totalPrice,2);
      }
      this.setData({
        tip: tip,
        coupon: item,
        totalPrice: totalPrice
      })
    }


  },
})